package com.peng.netty_test;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup(1);
        Bootstrap bootstrap = new Bootstrap();

        try {
            ChannelFuture channelFuture = bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            System.out.println("initChannel==>SocketChannel....");
                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    System.out.println("channelActive.....");
                                    ctx.writeAndFlush(Unpooled.copiedBuffer("hello".getBytes()));
                                }

                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                    ByteBuf buf = (ByteBuf) msg;

                                    System.out.println(buf.toString(CharsetUtil.UTF_8));
                                    ReferenceCountUtil.release(buf);//释放内存
                                }

                            });
                        }

                    })
                    .connect("localhost", 8888)
//                    .addListener(new ChannelFutureListener() {
//                        @Override
//                        public void operationComplete(ChannelFuture future) {
//                            if (!future.isSuccess()) {
//                                System.out.println("not connect...");
//                            } else {
//                                System.out.println("connected...");
//                            }
//                        }
//                    })
                    .sync();
            channelFuture.channel().closeFuture().sync();

        } finally {
            eventLoopGroup.shutdownGracefully();
        }


    }
}
